// packageB/pages/live/live.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    height: app.globalData.height,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '关于必站', //导航栏 中间的标题
    },
    videoUrl: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      videoUrl: options.vpUrl
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.videoContext = wx.createVideoContext('myVideo', this);// 	创建 video 上下文 VideoContext 对象。
		// this.videoContext.requestFullScreen({	// 设置全屏时视频的方向，不指定则根据宽高比自动判断。
		// 	direction: 90						// 屏幕逆时针90度
		// });
    
  },
// 视频结束后自动退出全屏
endAction: function () {
  this.videoContext = wx.createVideoContext('myVideo', this);
  this.videoContext.exitFullScreen(); //退出全屏
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;

  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  //   let that = this;
  //   return {
  //     title: that.data.name,
  //     path: '/packageB/pages/live/live?&share=true&spread_code=' + that.data.spread_code,
  //     imageUrl: that.data.share_pic,
  //     success: function (res) {
  //       wx.showToast({
  //         title: "已转发",
  //         icon: 'none',
  //         duration: 2000
  //       })
  //     }
  //   }
  // },
  filterViewMove() {
    return false;
  },
  getShare() {
    let that = this
    let data = {
      type: 6,
    }
    app.fly.get('mall/v1/common/share', data)
      .then(function (res) {
        if(res.data){
          that.setData({
            name: res.data.title,
            share_pic: res.data.icon
          })
        }else{
          that.setData({
            name: "菜友记直播",
            share_pic: "https://xunjiangzhimei.oss-cn-hangzhou.aliyuncs.com/upload/image/20200617/075283d4c997db6171b164d5ec12281d0c881a3d.png"
          })       
        }
      })
  },
  changeIdx(e){
    this.setData({
      idx:e.currentTarget.dataset.id
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  getList() {
    let that = this;
    app.fly.get('/v1/common/live/list')
      .then(function (res) {
        if (res.code == '200') {
          that.setData({
            list: res.data,
            isShow: true,
            showBottom: true,
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
  },
  goLive(e) {
    let that = this;
    let roomid = e.currentTarget.dataset.roomid;
    wx.navigateTo({
      url: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' + roomid
    })
  },
  toggleDialog_2() {
    this.setData({
      showlog_2: false,
    })
  },
  //分享生成海报
  shareFrends(e) {
    let that = this;
    wx.showLoading({
      title: '图片生成中',
    })
    if (that.data.token != "") {
      that.setData({
        share_pic: e.currentTarget.dataset.src
      })
      wx.getImageInfo({   // 根据头像地址下载头像并存为临时路径
        src: e.currentTarget.dataset.src,
        success: res => {
          that.setData({
            src: res.path
          })
        }
      })
      that.setData({
        name: e.currentTarget.dataset.name,
        roomid: e.currentTarget.dataset.roomid,
      })
      that.getLiveWxCode();
      //that.createdCode()

    } else {
      wx.navigateTo({
        url: '/packageD/pages/authorize/authorize'
      })
    }
  },
  getLiveWxCode() {
    let that = this;
    app.fly.post('mall/v1/common/miniLive/getLiveWxCode', {
      room_id: that.data.roomid,
    }).then(function (res) {
      if (res.code == '200') {
        wx.getImageInfo({   // 根据头像地址下载头像并存为临时路径
          src: res.data.live_code,
          success: ress => {
            that.setData({
              weima_pic: ress.path
            })
            that.createdCode()
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  createdCode() {
    let that = this;
    let rpx = 1;
    wx.getSystemInfo({
      success(res) {
        rpx = res.windowWidth / 375;
      },
    })
    const ctx = wx.createCanvasContext('shareFrends');
    let pichName = that.data.nickname;  //用户昵称
    // 绘制logo
    ctx.save()
    // canvas 背景颜色设置不成功，只好用白色背景图
    ctx.drawImage('../img/bg.png', 0, 0, 588 * rpx, 912 * rpx);
    ctx.font = 'normal bold 24rpx sans-serif';
    ctx.setFillStyle('#333334')
    ctx.fillText(pichName, 116 * rpx, 694 * rpx)
    ctx.drawImage(that.data.src, 28 * rpx, 210 * rpx, 530 * rpx, 424 * rpx);
    ctx.font = 'normal bold 24rpx sans-serif';
    ctx.setFillStyle('#333334')
    if (that.data.name.length > 15) {
      ctx.fillText(that.data.name.slice(0, 15) + "...", 28 * rpx, 818 * rpx);
    } else {
      ctx.fillText(that.data.name, 28 * rpx, 818 * rpx)
    }

    // ctx.arc(284, 307, 254, 0, Math.PI * 2, false);
    // ctx.clip();//画了圆 再剪切 原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
    ctx.arc(65 * rpx, 712 * rpx, 35 * rpx, 0, Math.PI * 2, false);
    ctx.clip();
    ctx.drawImage(that.data.ava_pic, 30 * rpx, 676 * rpx, 70 * rpx, 70 * rpx);
    ctx.restore();
    ctx.drawImage(that.data.weima_pic, 414 * rpx, 666 * rpx, 136 * rpx, 136 * rpx);

    // ctx.font = 'normal 300 22rpx sans-serif';
    // ctx.setFillStyle('#9B9B9B')
    // ctx.fillText("长按识别菜友记", 384 * rpx, 800 * rpx);
    ctx.draw()
    // that.setData({ showlog_2: true, })
    setTimeout(() => {
      // 将生成的canvas图片，转为真实图片
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        canvasId: 'shareFrends',
        success: function (res) {
          let shareImg = res.tempFilePath;
          console.log(res);
          that.setData(
            {
              shareImg: shareImg,
              showShareModal: false,
              showlog_2: true,
            }
          )
          wx.hideLoading()
        },
        fail: function (res) {
          console.log(1231231);
        }
      })
    }, 500)
  },
  //文字换行处理
  // canvas 标题超出换行处理
  wordsWrap(ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
    let lineWidth = 0;
    let lastSubStrIndex = 0;
    for (let i = 0; i < name.length; i++) {
      lineWidth += ctx.measureText(name[i]).width;
      if (lineWidth > maxWidth) {
        ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY);
        srartY += wordsHight;
        lineWidth = 0;
        lastSubStrIndex = i;
      }
      if (i == name.length - 1) {
        ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY);
      }
    }
  },
  roundRect(ctx, x, y, w, h, r) {
    // 开始绘制
    ctx.beginPath()
    // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
    // 这里是使用 fill 还是 stroke都可以，二选一即可
    ctx.setFillStyle('transparent')
    // ctx.setStrokeStyle('transparent')
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)

    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
  },
  // 保存图片到手机
  onSaveToPhone() {
    let that = this;
    wx.showLoading({
      title: '正在保存中',
      mask: true,
      duration: 2000,
    })
    if (!that.data.once) {
      return false;
    }
    that.setData({
      once: false,
    })
    that.getSetting().then((res) => {
      // 判断用户是否授权了保存到本地的权限
      if (!res.authSetting['scope.writePhotosAlbum']) {
        that.authorize().then(() => {
          wx.uploadFile({
            url: 'https://api.xunjiangzhimei.com/v1/common/ossUploadImage', //仅为示例，非真实的接口地址
            filePath: that.data.shareImg,
            name: 'file',
            formData: {
              'file': that.data.shareImg
            },
            success(res) {
              let obj = JSON.parse(res.data)
              let file = String(obj.data.file)

              that.savedownloadFile(file)
            }
          })
          that.setData({
            isAuthSavePhoto: false
          })
        }).catch(() => {
          wx.showToast({
            title: '您拒绝了授权',
            icon: 'none',
            duration: 1500
          })
          that.setData({
            isAuthSavePhoto: true
          })
        })
      } else {
        wx.uploadFile({
          url: 'https://api.xunjiangzhimei.com/v1/common/ossUploadImage', //仅为示例，非真实的接口地址
          filePath: that.data.shareImg,
          name: 'file',
          formData: {
            'file': that.data.shareImg
          },
          success(res) {
            let obj = JSON.parse(res.data)
            let file = String(obj.data.file)

            that.savedownloadFile(file)
          }
        })
        //
      }
    })
  },
  //打开设置，引导用户授权
  onOpenSetting() {
    let that = this;
    wx.openSetting({
      success: (res) => {
        console.log(res.authSetting)
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.showToast({
            title: '您未授权',
            icon: 'none',
            duration: 1500
          })
          that.setData({// 拒绝授权
            isAuthSavePhoto: true
          })

        } else {// 接受授权
          that.setData({
            isAuthSavePhoto: false
          })
          that.onSaveToPhone() // 接受授权后保存图片

        }

      }
    })

  },
  // 获取用户已经授予了哪些权限
  getSetting() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          resolve(res)
        }
      })
    })
  },
  // 发起首次授权请求
  authorize() {
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope: 'scope.writePhotosAlbum',
        success: () => {
          resolve()
        },
        fail: res => { //这里是用户拒绝授权后的回调
          console.log('拒绝授权')
          this.showModal();
          // reject()
        }
      })
    })
  },
  savedownloadFile(img) {
    let that = this;
    that.downLoadFile(img).then((res) => {
      return that.saveImageToPhotosAlbum(res.tempFilePath)
    }).then(() => {
      that.setData({
        once: true,
      })
    })
  },
  //单文件下载(下载文件资源到本地)，客户端直接发起一个 HTTPS GET 请求，返回文件的本地临时路径。
  downLoadFile(img) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: img,
        success: (res) => {
          console.log('downloadfile', res)
          resolve(res)
        },
        fail: function (res) {
          console.log(res)
        },
      })
    })
  },
  // 保存图片到系统相册
  saveImageToPhotosAlbum(saveUrl) {
    return new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath: saveUrl,
        success: (res) => {
          wx.showToast({
            title: '保存成功',
            duration: 1000,
          })
          resolve()
        }
      })
    })
  },
  // 弹出模态框提示用户是否要去设置页授权
  showModal() {
    wx.showModal({
      title: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
      success: (res) => {
        if (res.confirm) {
          console.log('用户点击确定')
          this.onOpenSetting() // 打开设置页面          
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
})